package com.ffcs.web.services;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.ffcs.web.daos.implementations.CounselorDao;
import com.ffcs.web.daos.implementations.DrawalDao;
import com.ffcs.web.daos.implementations.OrderDao;
import com.ffcs.web.daos.implementations.StudyDao;
import com.ffcs.web.daos.implementations.YuyueTempDao;
import com.ffcs.web.model.dto.CounselorOrder;
import com.ffcs.web.model.dto.OrderPing;
import com.ffcs.web.model.dto.Pingjia;
import com.ffcs.web.model.entity.Counselor;
import com.ffcs.web.model.entity.Drawal;
import com.ffcs.web.model.entity.Order;
import com.ffcs.web.model.entity.PingLun;
import com.ffcs.web.model.entity.Study;
import com.ffcs.web.model.entity.WxUser;
import com.ffcs.web.model.entity.YuyueTemp;
import com.ffcs.web.model.requests.AddOrderRequest;
import com.ffcs.web.utils.ChinaeseUtil;
import com.ffcs.web.utils.XingqiUtil;

/**
 * 订单相关逻辑
 * @author Administrator
 *
 */
@Service
public class OrderService {

	private Logger logger = Logger.getLogger(OrderService.class);
	
	@Autowired
	private OrderDao orderDao;
	@Autowired
	private StudyDao studyDao;
	@Autowired
	private CounselorDao counselorDao;
	@Autowired
	private JdbcTemplate jdbcTemplate;
	@Autowired
	private YuyueTempDao yuyueTempDao;
	@Autowired
	private DrawalDao drawalDao;
	
	@Transactional
	public Order saveOrder(WxUser wuser,AddOrderRequest addOrderRequest) {
		Order order=new Order();
		order.setOrderSn(new DateTime().toString("yyMMddHHmm") + RandomStringUtils.randomNumeric(6));//orderSn规则 yyMMdd+6位数字随机数
		order.setBookTime(new Date());
		
		int studyId=Integer.parseInt(addOrderRequest.getStudyId());
		Study study=studyDao.get(studyId);
		Assert.notNull(study);
		order.setCounseTel(study.getCounseTel());
		order.setCounseType("null");
		order.setDateAdd(new Date());
		order.setCounseName(study.getCounseName());
		order.setStudyId(studyId);
		order.setServiceTime("");
		order.setDateChange(new Date());
		order.setOrderPrice(study.getStudyPrice());
		order.setOrderStatus("5");//5代付款
		order.setOrderType(addOrderRequest.getOrderType());
		order.setPayMenthod(addOrderRequest.getPayMenthod());//微信:wei_pay
		order.setQuestionDesc("");
		order.setUserId(wuser.getId());
		order.setTelephone(addOrderRequest.getTelephone());
		
		if(!ChinaeseUtil.isChineseChar(addOrderRequest.getCustomerName())){
			String customerName="";
			try {
				customerName=new String(addOrderRequest.getCustomerName().getBytes("ISO-8859-1"),"UTF-8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			order.setCustomerName(customerName);
		}else{
			order.setCustomerName(addOrderRequest.getCustomerName());
		}
		orderDao.save(order);
		return order;
	}

	/**
	 * 获取订单信息
	 * @param orderSn
	 * @return
	 */
	public Order getOrder(String orderSn) {
		return orderDao.findUniqueByPropertyName("orderSn",orderSn);
	}
	/**
	 * 获取订单信息
	 * @param orderSn
	 * @return
	 */
	public Order getOrder(Integer orderId) {
		return orderDao.get(orderId);
	}

	/**
	 * 更改订单为已付款
	 * @param out_trade_no
	 */
	@Transactional
	public void updateOrderStatus(String out_trade_no) {
		Order order=orderDao.findUniqueByPropertyName("orderSn",out_trade_no);
		order.setDateChange(new Date());
		order.setOrderStatus("6");
		orderDao.save(order);
		logger.info("订单out_trade_no="+out_trade_no+"，状态已更改为已付款"+order.getOrderStatus());
	}
	
	/**
	 * 更新订单用户
	 * @param orderSn
	 * @param userId
	 */
	@Transactional
	public void updateOrderUserId(String orderSn,int userId) {
		Order order=orderDao.findUniqueByPropertyName("orderSn",orderSn);
		order.setUserId(userId);
		orderDao.save(order);
		logger.info("订单orderSn="+orderSn+"，用户已更新为微信用户userId="+userId);
	}

	/**
	 * 获取培训评价
	 * @param studyId
	 * @return
	 */
	public List<Pingjia> getPeiPingjia(String studyId) {
		String sql="select o.pingjia pingjia,o.pingjiaxx pingjiaxx,o.pingjiaTime pingjiaTime,u.nickname nickName,u.headimgurl headUrl from wechat_order o,wechat_user u where u.id=o.userId and studyId='"+studyId+"' and pingjia is not null order by o.pingjiaTime desc"; 
		return jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<Pingjia>(Pingjia.class));
	}

	/**
	 * 我的订单
	 * @param id
	 * @return
	 * @throws InvocationTargetException 
	 * @throws IllegalAccessException 
	 */
	public List<Order> getOrderbyUserId(Integer id,String orderStatus) throws IllegalAccessException, InvocationTargetException {
		
		List<CounselorOrder> counselorOrderList=new ArrayList<CounselorOrder>();
		List<Order> orderList=new ArrayList<Order>();
		if(null==orderStatus || "".equals(orderStatus)){
			orderList=orderDao.findByPropertyNameWithOrder("userId",id,"dateAdd",false);
		}else{
			String sql="";
			if(orderStatus.equals("weiwangcheng")){
				sql="select * from wechat_order where userId="+id+" and orderStatus=5 order by dateAdd desc";
			}else if(orderStatus.equals("daipingjia")){
				sql="select * from wechat_order where userId="+id+" and orderStatus4 and orderStatus=2  order by dateAdd desc";
			}else if(orderStatus.equals("yiwangcheng")){
				sql="select * from wechat_order where userId="+id+" and orderStatus=3  order by dateAdd desc";
			}
			orderList=jdbcTemplate.query(sql, new BeanPropertyRowMapper<Order>(Order.class));
		}
//		for (Order order : orderList) {
//			CounselorOrder counselorOrder=new CounselorOrder();
//			Counselor counselor=counselorDao.findUniqueByPropertyName("counseTel",order.getCounseTel());
//			BeanUtils.copyProperties(counselorOrder, counselor);
//			BeanUtils.copyProperties(counselorOrder, order);
//			counselorOrderList.add(counselorOrder);
//		}
		return orderList;
	}

	@Transactional
	public YuyueTemp addYuYueTemp(String counseTel, String question,
			String counseType, String bookTime, String bookDay,String buyTime,WxUser wuser,String type) {
		
		YuyueTemp yuyueTemp=new YuyueTemp();
		yuyueTemp.setCounseTel(counseTel);
		yuyueTemp.setBuyTime(buyTime);
		String bookTimes="";
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		
		if(!ChinaeseUtil.isChineseChar(counseType)){
			try {
				counseType=new String(counseType.getBytes("ISO-8859-1"),"UTF-8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		yuyueTemp.setCounseType(counseType);
		if(!ChinaeseUtil.isChineseChar(question)){
			try {
				question=new String(question.getBytes("ISO-8859-1"),"UTF-8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		yuyueTemp.setQuestion(question);
		yuyueTemp.setType(type);
		yuyueTemp.setUserId(wuser.getId());
		if("".equals(bookDay) || null==bookDay){
			bookTimes=sdf.format(new Date());
		}else{
			int xingqi=Integer.parseInt(XingqiUtil.getWeekOfDate(new Date()));
			int bookXingqi=Integer.parseInt(bookDay);
			if(xingqi==bookXingqi){
				bookTimes=sdf.format(new Date());
			}else if(xingqi==(bookXingqi+1)){
				Calendar calendar = Calendar.getInstance();
				calendar.setTime(new Date());
				calendar.add(Calendar.DATE, +6);
				Date date=calendar.getTime();
				bookTimes=sdf.format(date);
			}else if(xingqi==(bookXingqi+2)){
				Calendar calendar = Calendar.getInstance();
				calendar.setTime(new Date());
				calendar.add(Calendar.DATE, +5);
				Date date=calendar.getTime();
				bookTimes=sdf.format(date);
			}else if(xingqi==(bookXingqi+3)){
				Calendar calendar = Calendar.getInstance();
				calendar.setTime(new Date());
				calendar.add(Calendar.DATE, +4);
				Date date=calendar.getTime();
				bookTimes=sdf.format(date);
			}else if(xingqi==(bookXingqi+4)){
				Calendar calendar = Calendar.getInstance();
				calendar.setTime(new Date());
				calendar.add(Calendar.DATE, +3);
				Date date=calendar.getTime();
				bookTimes=sdf.format(date);
			}else if(xingqi==(bookXingqi+5)){
				Calendar calendar = Calendar.getInstance();
				calendar.setTime(new Date());
				calendar.add(Calendar.DATE, +2);
				Date date=calendar.getTime();
				bookTimes=sdf.format(date);
			}else if(xingqi==(bookXingqi+6)){
				Calendar calendar = Calendar.getInstance();
				calendar.setTime(new Date());
				calendar.add(Calendar.DATE, +1);
				Date date=calendar.getTime();
				bookTimes=sdf.format(date);
			}else if(xingqi==(bookXingqi-1)){
				Calendar calendar = Calendar.getInstance();
				calendar.setTime(new Date());
				calendar.add(Calendar.DATE, +1);
				Date date=calendar.getTime();
				bookTimes=sdf.format(date);
			}else if(xingqi==(bookXingqi-2)){
				Calendar calendar = Calendar.getInstance();
				calendar.setTime(new Date());
				calendar.add(Calendar.DATE, +2);
				Date date=calendar.getTime();
				bookTimes=sdf.format(date);
			}else if(xingqi==(bookXingqi-3)){
				Calendar calendar = Calendar.getInstance();
				calendar.setTime(new Date());
				calendar.add(Calendar.DATE, +3);
				Date date=calendar.getTime();
				bookTimes=sdf.format(date);
			}else if(xingqi==(bookXingqi-4)){
				Calendar calendar = Calendar.getInstance();
				calendar.setTime(new Date());
				calendar.add(Calendar.DATE, +4);
				Date date=calendar.getTime();
				bookTimes=sdf.format(date);
			}else if(xingqi==(bookXingqi-5)){
				Calendar calendar = Calendar.getInstance();
				calendar.setTime(new Date());
				calendar.add(Calendar.DATE, +5);
				Date date=calendar.getTime();
				bookTimes=sdf.format(date);
			}else if(xingqi==(bookXingqi-6)){
				Calendar calendar = Calendar.getInstance();
				calendar.setTime(new Date());
				calendar.add(Calendar.DATE, +6);
				Date date=calendar.getTime();
				bookTimes=sdf.format(date);
			}else{
				bookTimes=sdf.format(new Date());
			}
			
		}
		
		bookTimes+=" "+replaceBlank(bookTime);
		yuyueTemp.setBookTime(bookTimes);
		yuyueTempDao.save(yuyueTemp);
		return yuyueTemp;
	}
	
	public static String replaceBlank(String str) {
        String dest = "";
        if (str!=null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }
	
	public YuyueTemp getYuyueTemp(String yuyueId) {
		YuyueTemp yuyueTemp=yuyueTempDao.get(Integer.parseInt(yuyueId));
		return yuyueTemp;
	}
	
	/**\
	 * 预约订单
	 * @param yuyueId
	 * @param wuser
	 * @return
	 */
	@Transactional
	public Order saveOrder(String yuyueId, WxUser wuser) {
		
		Order order=new Order();
		order.setOrderSn(new DateTime().toString("yyMMddHHmm") + RandomStringUtils.randomNumeric(6));//orderSn规则 yyMMdd+6位数字随机数
		
		YuyueTemp yuyueTemp=yuyueTempDao.get(Integer.parseInt(yuyueId));
		Assert.notNull(yuyueTemp);
		Counselor counselor=counselorDao.findUniqueByPropertyName("counseTel",yuyueTemp.getCounseTel());
		Assert.notNull(counselor);
		
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm");
		try {
			order.setBookTime(sdf.parse(yuyueTemp.getBookTime()));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		order.setCounseTel(yuyueTemp.getCounseTel());
		if(yuyueTemp.getCounseType().equals("电话咨询")){
			order.setCounseType("1");
		}else if(yuyueTemp.getCounseType().equals("面对面咨询")){
			order.setCounseType("2");
		}else{
			order.setCounseType("3");
		}
		order.setDateAdd(new Date());
		order.setCounseName(counselor.getCounseName());
		order.setServiceTime(yuyueTemp.getBuyTime());
		order.setDateChange(new Date());
		if("15".equals(yuyueTemp.getBuyTime())){
			order.setOrderPrice(counselor.getServicePrice15());
		}else{
			order.setOrderPrice(counselor.getServicePrice40());
		}
		order.setOrderStatus("5");//5代付款
		order.setOrderType("1");
		order.setPayMenthod("wei_pay");//微信:wei_pay
		order.setQuestionDesc("");
		order.setUserId(wuser.getId());
		
		Order orderExample=new Order();
		SimpleDateFormat sdf2=new SimpleDateFormat("yyyy-MM-dd");
		try {
			if(yuyueTemp.getBookTime().contains("24:00")){
				
				Date date22=sdf2.parse(yuyueTemp.getBookTime());
				Calendar calendar = Calendar.getInstance();
				calendar.setTime(date22);
				calendar.add(Calendar.DATE, +1);
				Date date=calendar.getTime();
				String bookTimes2=sdf.format(date);
				System.out.println(bookTimes2+" 00:00");
				System.out.println(bookTimes2+" 00:00");
				System.out.println(bookTimes2+" 00:00");
				System.out.println(bookTimes2+" 00:00");
				System.out.println(bookTimes2+" 00:00");
				
				orderExample.setBookTime(sdf2.parse(bookTimes2+" 00:00"));
			}else{
				orderExample.setBookTime(sdf.parse(yuyueTemp.getBookTime()));
			}
			
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		orderExample.setCounseTel(yuyueTemp.getCounseTel());
		List<Order> list=orderDao.findByExample(orderExample);
		for (Order order2 : list) {
			if(!order2.getOrderStatus().equals("5") && !order2.getOrderStatus().equals("4") && !order2.getOrderStatus().equals("7")){
				logger.info("订单时间："+order2.getBookTime()+","+yuyueTemp.getCounseTel()+"已被占用");
				return null;
			}else if(order2.getOrderStatus().equals("5")){
				logger.info("其他订单orderSn--->"+order2.getOrderSn()+"未支付的，自动作废");
				order2.setOrderStatus("7");
				orderDao.save(order2);
			}
		}
		orderDao.save(order);
		return order;
	}

	/**
	 * 补充订单资料
	 * @param orderSn
	 * @param wxUser
	 * @param age
	 * @param schoolAge
	 * @param sex
	 * @param marr
	 */
	@Transactional
	public void buChongOrder(String orderSn,String age,
			String schoolAge, String sex, String marr,String customerName,String telephone) {
		Order order=orderDao.findUniqueByPropertyName("orderSn",orderSn);
		Assert.notNull(order);
		marr=replaceBlank(marr);
		order.setMarriage(Short.parseShort(marr));
		order.setAge(Short.parseShort(age));
		order.setSchoolAge(Short.parseShort(schoolAge));
		order.setSex(Short.parseShort(sex));
		order.setCustomerName(ChinaeseUtil.CharTOChinaese(customerName));
		order.setTelephone(telephone);
		orderDao.save(order);
		logger.info("用户:"+customerName+"补充订单:"+orderSn+"用户信息成功");
	}

	public List<Order> getMyCounselorOrder(String counseTel,
			String orderStatus,String orderType) {
		List<Order> orderList=new ArrayList<Order>();
		List<Order> orderList2=new ArrayList<Order>();
		if(null==orderStatus || "".equals(orderStatus)){
			orderList=orderDao.findByPropertyNameWithOrder("counseTel",counseTel,"dateAdd",false);
			for (Order order : orderList) {
				if(order.getOrderType().equals("1") && !order.getOrderStatus().equals("5") && !order.getOrderStatus().equals("7")){
					orderList2.add(order);
				}
			}
		}else{
			String sql="";
			if(orderStatus.equals("weiwangcheng")){
				sql="select * from wechat_order where counseTel="+counseTel+" and (orderStatus=6 or orderStatus=0 or orderStatus=1) order by dateAdd desc";
			}else if(orderStatus.equals("daipingjia")){
				sql="select * from wechat_order where counseTel="+counseTel+" and (orderStatus=2 or orderStatus=4) order by dateAdd desc";
			}else if(orderStatus.equals("yiwangcheng")){
				sql="select * from wechat_order where counseTel="+counseTel+" and orderStatus=3  order by dateAdd desc";
			}
			System.out.println(sql);
			orderList=jdbcTemplate.query(sql, new BeanPropertyRowMapper<Order>(Order.class));
			for (Order order : orderList) {
				if(order.getOrderType().equals("1") && !order.getOrderStatus().equals("5") && !order.getOrderStatus().equals("7")){
					orderList2.add(order);
				}
			}
		}
		return orderList2;
	}

	public String getMyYuer(String counseTel) {
		Order order=new Order();
		order.setCounseTel(counseTel);
		Double price=0d;
		List<Order> list=orderDao.findByExample(order);
		for (Order o : list) {
			if(o.getOrderStatus().equals("2") || o.getOrderStatus().equals("3")){
				price+=o.getOrderPrice();
			}
		}
		Double priced=0d;
		List<Drawal> drawalList=drawalDao.findByPropertyName("counseTel",counseTel);
		for (Drawal drawal : drawalList) {
			if(drawal.getType()==0 && drawal.getStatus()!=2){
				priced+=drawal.getMoney();
			}
		}
		System.out.println(price);
		System.out.println(priced);
		DecimalFormat df = new DecimalFormat("######0.00");
		return df.format(price-priced)+"";
	}

	/**
	 * 添加体现记录
	 * @param money
	 * @param account
	 * @param bankName
	 * @param payChannel
	 * @param counselor
	 */
	@Transactional
	public void addTixian(String money, String account, String bankName,
			String payChannel, Counselor counselor) {
		Drawal drawal=new Drawal();
		if(payChannel.equals("1")){
			drawal.setAccount(account);
		}else{
			drawal.setAccount(account);
			drawal.setBankName(ChinaeseUtil.CharTOChinaese(bankName));
		}
		drawal.setPayChannel(Integer.parseInt(payChannel));
		drawal.setMoney(Double.parseDouble(money));
		drawal.setCounseName(counselor.getCounseName());
		drawal.setCounseTel(counselor.getCounseTel());
		drawal.setDate(new Date());
		drawal.setStatus(0);
		drawal.setType(0);
		drawalDao.save(drawal);
	}

	public List<Drawal> getTixianJilu(String counseTel) {
		List<Drawal> list2=new ArrayList<Drawal>();
		List<Drawal> list= drawalDao.findByPropertyNameWithOrder("counseTel",counseTel, "date",false);
		for (Drawal drawal : list) {
			if(drawal.getType()==0){
				list2.add(drawal);
			}
		}
		return list2;
	}

	public String getYesterday(String counseTel,String num) {
		String sql="";
		if(num.equals("30")){
			sql="select ifnull(sum(t.orderPrice),0) from wechat_order t where (t.orderStatus=2 or t.orderStatus=3) and DATE(t.dateChange)>=DATE_ADD(curdate(),INTERVAL -1 MONTH) and counseTel="+counseTel;
		}else if(num.equals("300")){
			sql="select ifnull(sum(t.orderPrice),0) from wechat_order t where (t.orderStatus=2 or t.orderStatus=3) and counseTel="+counseTel;
		}else if(num.equals("1")){
			sql="select ifnull(sum(t.orderPrice),0) from wechat_order t where (t.orderStatus=2 or t.orderStatus=3) and DATE(t.dateChange)=DATE_ADD(curdate(),INTERVAL -1 day) and counseTel="+counseTel;
		}else{
			sql="select ifnull(sum(t.orderPrice),0) from wechat_order t where (t.orderStatus=2 or t.orderStatus=3) and DATE(t.dateChange)>=DATE_ADD(curdate(),INTERVAL -"+num+" day) and counseTel="+counseTel;
		}
		System.out.println(sql);
		Map<String, Object> map=jdbcTemplate.queryForMap(sql);
		Set<Entry<String, Object>> entrySet=map.entrySet();
		for (Entry<String, Object> entry : entrySet) {
			return entry.getValue()+"";
		}
		return "0";
	}

	/**
	 * 获取培训情况
	 * @param studyId
	 * @param getBaoming
	 * @return
	 */
	public List<Order> getBaoming(String studyId, String getBaoming) {
		String sql="";
		if(getBaoming.equals("0")){
			sql="select * from wechat_order t where t.orderType=3 and t.studyId="+studyId+" and ( t.orderStatus=0 or  t.orderStatus=6) order by t.bookTime desc";
		}else{
			sql="select * from wechat_order t where t.orderType=3 and t.studyId="+studyId+" and ( t.orderStatus=1 or  t.orderStatus=2 or t.orderStatus=3) order by t.bookTime desc";
		}
		return jdbcTemplate.query(sql, new BeanPropertyRowMapper<Order>(Order.class));
	}

	@Transactional
	public void updatePeixunOrder(String orderId,String status) {
		Order order=orderDao.get(Integer.parseInt(orderId));
		order.setOrderStatus(status);
		orderDao.save(order);
	}

	@Transactional
	public void updatePeixunOrder(String orderId, String mark,Double orderPrice) {
		String sql1="update wechat_order set orderStatus='4' where id="+orderId;
		jdbcTemplate.update(sql1);
		String sql2="insert wechat_order_failure (orderId,mark,tuiMoney) values('"+orderId+"','"+ChinaeseUtil.CharTOChinaese(mark)+"','"+orderPrice+"')";
		jdbcTemplate.update(sql2);
		logger.info("[orderId="+orderId+"]--->新增订单作废记录");
	}

	@Transactional
	public void addWeixinStream(String appid, String bank_type,
			String cash_fee, String fee_type, String is_subscribe,
			String mch_id, String nonce_str, String openid,
			String out_trade_no, String result_code, String return_code,
			String sign, String time_end, String time_end2, String total_fee,
			String trade_type, String transaction_id) {
		 String sql2="insert wechat_weixin_stream value ('"+appid+"','"+bank_type+"','"+cash_fee+"','"+fee_type+"','"+is_subscribe+"','"+mch_id+"','"+nonce_str+"','"+openid+"','"+out_trade_no+"','"+result_code+"','"+return_code+"','"+sign+"','"+time_end+"','"+time_end2+"','"+total_fee+"','"+trade_type+"','"+transaction_id+"')";
		 logger.info(sql2);
		 jdbcTemplate.update(sql2);
		logger.info("[orderSn="+out_trade_no+"]--->保存微信订单支付记录");
	}

	@Transactional
	public void updateOrderFailure(String orderId, String refundMark) {
		String sql2="update wechat_order_failure set refundMark='"+refundMark+"' where orderId="+orderId;
		jdbcTemplate.update(sql2);
		logger.info("[orderId="+orderId+"]--->退款成功，插入记录");
	}

	
	public List<Order> getOrderList(String counseTel, String flag) {
		String sql="";
		if(flag.equals("30")){
			sql="select * from wechat_order t where (t.orderStatus=2 or t.orderStatus=3) and DATE(t.dateChange)>=DATE_ADD(curdate(),INTERVAL -1 MONTH) and counseTel="+counseTel;
		}else if(flag.equals("300")){
			sql="select * from wechat_order t where (t.orderStatus=2 or t.orderStatus=3) and counseTel="+counseTel;
		}else if(flag.equals("1")){
			sql="select * from wechat_order t where (t.orderStatus=2 or t.orderStatus=3) and DATE(t.dateChange)=DATE_ADD(curdate(),INTERVAL -1 day) and counseTel="+counseTel;
		}else{
			sql="select * from wechat_order t where (t.orderStatus=2 or t.orderStatus=3) and DATE(t.dateChange)>=DATE_ADD(curdate(),INTERVAL -"+flag+" day) and counseTel="+counseTel;
		}
		return jdbcTemplate.query(sql, new BeanPropertyRowMapper<Order>(Order.class));
	}
	
	public List<OrderPing> getOrderPingjiaList(String counseTel) {
		String sql="select t.pingjia,t.pingjiaTime,t.pingjiaxx,u.nickname,u.headimgurl from wechat_order t ,wechat_user u where t.userId=u.id and t.orderStatus=3 and counseTel='"+counseTel+"' order by pingjiaTime desc";
		return jdbcTemplate.query(sql, new BeanPropertyRowMapper<OrderPing>(OrderPing.class));
	}

	@Transactional
	public void updateCanYuyue(Order order) {
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH");
		SimpleDateFormat sdf2=new SimpleDateFormat("yyyy-MM-dd");
		String btime[]=sdf.format(order.getBookTime()).split(" ");
		if(btime[1].equals("00")){
			btime[1]="24";
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(order.getBookTime());
			calendar.add(Calendar.DATE, -1);
			Date date=calendar.getTime();
			btime[0]=sdf2.format(date);
		}
		String sql2="update wechat_canYuyue set status=0 where canDate='"+btime[0]+"' and canTime='"+btime[1]+"' and counseTel="+order.getCounseTel();
		jdbcTemplate.update(sql2);
	}
	
	public static void main(String[] args) {
		String s="2015-10-28 00:00:00";
		SimpleDateFormat sdf2=new SimpleDateFormat("yyyy-MM-dd HH");
		Date d=null;
		try {
			d=sdf2.parse(s);
		} catch (ParseException e) {
			e.printStackTrace();
		}
//		Date d=new Date();
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH");
		SimpleDateFormat sdf3=new SimpleDateFormat("yyyy-MM-dd");
		String btime[]=sdf.format(d).split(" ");
		System.out.println(btime[0]);
		System.out.println(btime[1]);
		if(btime[1].equals("00")){
			btime[1]="24";
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(new Date());
			calendar.add(Calendar.DATE, -1);
			Date date=calendar.getTime();
			btime[0]=sdf3.format(date);
		}
		System.out.println(btime[0]);
		System.out.println(btime[1]);
	}

	@Transactional
	public void pingjiaOrder(String orderSn, String pingjiaxx, String pingjia) {
		Order order=orderDao.findUniqueByPropertyName("orderSn",orderSn);
		order.setPingjiaxx((short)Integer.parseInt(pingjiaxx));
		order.setPingjia(ChinaeseUtil.CharTOChinaese(pingjia));
		order.setPingjiaTime(new Date());
		order.setOrderStatus("3");
	}

	@Transactional
	public void saveYuyueTemp(YuyueTemp yuyueTemp) {
		yuyueTempDao.save(yuyueTemp);
	}
	
	@Transactional
	public void deleteOrder(String orderId) {
		orderDao.removeById(Integer.parseInt(orderId));
	}
	
}
